//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useState } from 'react';
import { ReadOnlyEditor } from '@/components/Editor';
import RenderDocBtns from './RenderDocBtns';
import DocTocPanel from './DocTocPanel';
import s from "./EditDoc.module.less";
import { Card, Space } from 'antd';
import { TocInfo } from '@/components/Editor/extensions/TocExtension';
import { useDocStores } from '../store';
import { observer } from 'mobx-react';
import { watch, unwatch, WATCH_TARGET_ENTRY } from '@/api/project_watch';
import { get_session } from '@/api/user';
import { request } from '@/utils/request';


const ReadDoc: React.FC = () => {
  const store = useDocStores();

  const [matchKeywordList, setMatchKeywordList] = useState<string[]>([]);
  const [tocList, setTocList] = useState<TocInfo[]>([]);

  const watchDoc = async () => {
    const sessionId = await get_session();
    await request(watch({
      session_id: sessionId,
      project_id: store.projectId,
      target_type: WATCH_TARGET_ENTRY,
      target_id: store.docId,
    }));
  };

  const unwatchDoc = async () => {
    const sessionId = await get_session();
    await request(unwatch({
      session_id: sessionId,
      project_id: store.projectId,
      target_type: WATCH_TARGET_ENTRY,
      target_id: store.docId,
    }));
  };

  return (
    <Card title={
      <Space>
        <span className={store.entry?.my_watch == true ? s.isCollect : s.noCollect}
          onClick={e => {
            e.stopPropagation();
            e.preventDefault();
            if (store.entry?.my_watch == true) {
              unwatchDoc();
            } else {
              watchDoc();
            }
          }} />
        <span style={{ fontSize: "16px", fontWeight: 700 }}>{store.entry?.entry_title ?? ""}</span>
      </Space>
    }
      extra={<RenderDocBtns keyWordList={matchKeywordList} />} bordered={false}
      bodyStyle={{ paddingBottom: "0px", width: "calc(100vw - 10px)" }}>
      <div className={s.doc_wrap}>
        {tocList.length > 0 && <DocTocPanel tocList={tocList} />}
        <div className={s.read_doc}>
          {<ReadOnlyEditor content={store.doc?.base_info.content ?? ""} keywordList={store.keywordList}
            keywordCallback={(kwList) => setMatchKeywordList(kwList)}
            tocCallback={(result) => setTocList(result)} />}
        </div>
      </div>
    </Card>
  );
};

export default observer(ReadDoc);
